//标记是否在driver块上触发点击事件
function disableIndexDriverBlockFlag(flag){
	indexDriverBlockFlag = flag;
}

// 给驱动块绑定事件
function bindClickEventForDriverBlock(){
	// 驱动编辑
	$(".driver_group").click(function(){
		if('block'==$(this).attr("attr") && indexDriverBlockFlag){
			// 加载页面
			$initContainer.load($basePath+'/driver/page/driverEdit?dirverName='+$(this).attr("id"));
		}
		disableIndexDriverBlockFlag(true);
	});
}

// 启动驱动
function bindClickEventForLiveBtn(){
	$(".driver_group .live").click(function(){
		disableIndexDriverBlockFlag(false);
		
		var driverName = $(this).attr("driverName");
		var driverUrl = $(this).attr("driverUrl");
		$.post($basePath + driverUrl, {"name":driverName}, function(data) {
			if(data.success==true){
				// 加载页面
				$initContainer.load($basePath+'/index');
				bootGrowl(data.resultValue,"success"); 
			}else{
				bootGrowl(data.resultValue,"danger"); 
			}
		});
	});
}

// 禁用驱动
function bindClickEventForDisableBtn(){
	$(".driver_group .disable").click(function(){
		disableIndexDriverBlockFlag(false);
		
		var driverName = $(this).attr("attr");
		var $this = $(this);
		// 确认框确认是否禁用
		if($this.context.textContent!="禁用"){
			// 如果当前为禁用状态
			enableDiver(driverName, $this);
			return;
		}
		// 如果当前为恢复状态
		BootstrapDialog.show({
			title : "提示",
			type : BootstrapDialog.TYPE_DANGER,
			message : "确认禁用驱动之后将不再同步？",
			size:BootstrapDialog.SIZE_NORMAL,
			buttons : [{
				label : "确定",
				action : function(dialog){
					// 点击弹出框确认禁用后禁用驱动
					enableDiver(driverName, $this);
					dialog.close();
				}
				},{
					label : "取消",
					action : function(dialog){			    
					dialog.close();
				}
			}]
		});	
	});
}

// 点击弹出框确认禁用后禁用驱动
function enableDiver(driverName, $this){
	$.post($basePath + "/driver/enable", {"name":driverName}, function(data) {
		if(data.success==true){
			// 切换驱动状态
			changeDriverEnableState($this);
			bootGrowl(data.resultValue,"success"); 
		}else{
			bootGrowl(data.resultValue,"danger"); 
		}
	});
}

// 切换驱动状态
function changeDriverEnableState($this){
	// 驱动名称
	var driverName = $this.attr("attr");
	var $dirver = $("#"+driverName);
	
	// 当前状态
	var state = $this.attr("enabled");
	
	// 恢复/禁用文本
	var enabledHtml = "<span class='fa fa-check'></span>恢复";
	var disabledHtml = "<span class='fa fa-close'></span>禁用";
	
	// 按钮属性
	var attrEnable = 'true';
	var attrDisable = 'false';
	
	// 右上角删除按钮
	var showDelBtn = 'fa fa-trash-o fa-2x pull-right delete';
	var hideDelBtn = 'fa fa-trash-o fa-2x pull-right delete hidden';
	var delBtn = $dirver.find(".delete");
	
	// 中间图标
	var enabledIcon = 'fa fa-arrow-right fa-3x center-icon';
	var disabledIcon = 'fa fa-remove fa-3x center-icon text-warning';
	var centerIcon = $dirver.find(".center-icon");
	
	// 启动按钮
	var liveBtn = $dirver.find(".live");
	
	// 当前为恢复
	if('true'==state){
		// 变为禁用属性
		$this.attr("enabled", attrDisable);
		$this.html(enabledHtml);
		// 隐藏删除按钮
		delBtn.attr('class', showDelBtn);
		// 中间图标
		centerIcon.attr('class', disabledIcon);
		// 启动按钮
		liveBtn.attr("disabled","true");
		return;
	}

	// 当前为禁用
	if('false'==state){
		// 变为恢复属性
		$this.attr("enabled", attrEnable);
		$this.html(disabledHtml);
		// 显示删除按钮
		delBtn.attr('class', hideDelBtn);
		// 中间图标
		centerIcon.attr('class', enabledIcon);
		// 启动按钮
		liveBtn.removeAttr("disabled");
	}
	
}

// 删除驱动
function bindClickEventForDeleteBtn(){
	$(".driver_group .delete").click(function(){
		disableIndexDriverBlockFlag(false);
		var driverName = $(this).attr("attr");
		var $this = $(this);
		
		// 确认框确认是否删除
		BootstrapDialog.show({
			title : "提示",
			type : BootstrapDialog.TYPE_DANGER,
			message : "删除驱动之后将不再同步？",
			size:BootstrapDialog.SIZE_NORMAL,
			buttons : [{
				label : "确定",
				action : function(dialog){
					deleteDriver(driverName, $this);
					dialog.close();
				}
				},{
					label : "取消",
					action : function(dialog){			    
					dialog.close();
				}
			}]
		});
		
	});
}

// 点击弹出框确认删除后删除驱动
function deleteDriver(driverName,info){
	$.post($basePath + "/driver/delete", {"name":driverName}, function(data) {
		if(data.success==true){
			// 加载页面
			$initContainer.load($basePath+'/index');
			bootGrowl(data.resultValue,"success"); 
		}else{
			// 请求失败
			bootGrowl(data.resultValue,"danger"); 
		}
	});
}

// 下载错误
function bindClickEventForDownloadBtn(){
	$(".driver_group .download").click(function(){
		disableIndexDriverBlockFlag(false);
		bootGrowl('下载成功!',"success"); 
	});
}

// 给驱动绑定事件
function bindClickEventForDriver(){
	// 给驱动块绑定事件
	bindClickEventForDriverBlock();
	// 启动驱动
	bindClickEventForLiveBtn();
	// 禁用驱动
	bindClickEventForDisableBtn();
	// 删除驱动
	bindClickEventForDeleteBtn();
	// 下载错误
	bindClickEventForDownloadBtn();
}

function showDirverList(driver){
	// 恢复文本
	var enabledHtml = "<span class='fa fa-check'></span>恢复";
	// 禁用文本
	var disabledHtml = "<span class='fa fa-close'></span>禁用";
	var enableText = driver.enable ?  disabledHtml : enabledHtml;
	// 是否禁用
	var showDelBtn = driver.enable ? 'hidden' : '';
	
	// 中间图标
	var enabledIcon = "class='fa fa-arrow-right fa-3x center-icon'";
	var disabledIcon = "class='fa fa-remove fa-3x center-icon text-warning'";
	var enableIconText = driver.enable ? enabledIcon : disabledIcon;

	// 恢复/禁用启动按钮
	var liveBtnHtml = "";
	var disLiveBtnHtml = " disabled='disabled' ";
	var liveBtnText = driver.enable ?  liveBtnHtml : disLiveBtnHtml;
	
	// 启动按钮文本
	var startBtnText = "<button type='button' class='btn btn-success live' driverName='"+ driver.name +"' driverUrl='/driver/start' "+ liveBtnText +"><span class='fa fa-check'></span>启动</button>";
	var stopBtnText = "<button type='button' class='btn btn-warning live' driverName='"+ driver.name +"' driverUrl='/driver/stop' "+ liveBtnText +"><span class='fa fa-check'></span>停止</button>";
	var startOrStopBtnHtml = driver.run ? stopBtnText : startBtnText;
	
	// 计算进度
	var process = parseInt(driver.process);
	var processCompleted = parseInt(driver.processCompleted);
	var percent = Math.round(processCompleted / process * 10000) / 100.00 + '%';
	// 耗时
	var runTimeText = driver.runTime == null ? '0' : driver.runTime;
	// 运行时间
	var startDateStrHtml = "已运行"+driver.startDateStr;
	// 错误记录
	var showErrorHtml = " <a href='"+$basePath+"/driver/download?name="+ driver.name +"' class='download' title='下载错误日志' style='color:#990;' >下载错误日志("+ driver.error +")</a>";
	var driverErrorText = parseInt(driver.error) > 0 ? showErrorHtml:'';
	
	var html= "";
	html += "<div class='row container'>";
	html += "<div id="+ driver.name +" class='panel panel-info driver_group' attr='block' >";
	html += "<div class='panel-heading'>";
	html += "驱动名称："+ driver.name + "&nbsp;&nbsp;" +startDateStrHtml +"<span class='fa fa-trash-o fa-2x pull-right delete "+ showDelBtn +" text-warning' attr='"+ driver.name +"'></span>";
	html += "</div>";
	
	html += "<div class='panel-body'>";
	html += "<div class='row'>";
	html += "<!-- 数据源连接器 -->";
	html += "<div class='col-md-5'>";
	html += "<div class='panel '>";
	html += "<div class='panel-body'>";
	html += "<div class='row'>";
	html += "<div class='col-md-2'><span class='fa "+ DriverConnectorConstant[driver.sourceConnector]['icon'] +" fa-4x'></span></div>";
	html += "<div class='col-md-10'>";
	html += "<p>类&nbsp;&nbsp;&nbsp;型:"+ DriverConnectorConstant[driver.sourceConnector]['type'] +"</p>";
	html += "<p>数据源:"+ driver.sourceConfig.table +"</p>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";

	html += "<!-- 中间图标 -->";
	html += "<div class='col-md-2 text-center outer'>";
	html += "<br /><span "+enableIconText+"></span>";
	html += "</div>";
	
	html += "<!-- 目标源连接器 -->";
	html += "<div class='col-md-5'>";
	html += "<div class='panel '>";
	html += "<div class='panel-body'>";
	html += "<div class='row'>";
	html += "<div class='col-md-2'><span class='fa "+ DriverConnectorConstant[driver.targetConnector]['icon'] +" fa-4x'></span></div>";
	html += "<div class='col-md-10'>";
	html += "<p>类&nbsp;&nbsp;&nbsp;型:"+ DriverConnectorConstant[driver.targetConnector]['type'] +"</p>";
	html += "<p>目标源:"+ driver.targetConfig.table +"</p>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
				
	html += "<div class='row'>";
	html += "<div class='col-md-12'>";
	html += "<p>同步数据量:"+ driver.sourceRowCount +"条, 耗时:"+ runTimeText +"毫秒</p>";
	html += "<div class='progress progress-striped active'>";
	html += "<div class='progress-bar progress-bar-success timer' role='progressbar' title='总进度:"+ process +",已完成:"+ processCompleted +"' ";
	html += "style='width: "+ percent +"'>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
				
	html += "<div class='row'>";
	html += "<div class='col-md-9'>成功:"+ driver.success +", 失败:"+ driver.fail +"<br />"+ driverErrorText +"</div>";
	html += "<div class='col-md-3 text-right outer'>";
	html += startOrStopBtnHtml + "&nbsp;<button type='button' class='btn btn-info disable' attr='"+ driver.name +"' enabled='"+ driver.enable +"'>"+ enableText +"</button>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	return html;
}

// 更新驱动列表实时状态
function refreshDriversList(){
	// 保存驱动配置
	$.post($basePath + "/index/getDriverAll", function(data) {
        if(data.success==true){
        	var drivers = data.resultValue;
    		var driversLen = drivers.length;
    		var listHtml = '';
    		for (var i = 0; i < driversLen; i++) {
    			listHtml += showDirverList(drivers[i]);
    		}
    		$("#dirverList").html(listHtml);

            // 重新绑定驱动事件
            bindClickEventForDriver();
		}else{
			// 请求失败
			bootGrowl(data.resultValue,"danger"); 
		}
	});
}

$(function() {
	// 更新驱动列表实时状态
	refreshDriversList();
	
	// $$monitorFreshListIntervalStarted变量防止$initContainer.load($basePath+'/index');加载后，导致定时任务刷新JS被重复执行
	if(!$monitorFreshListIntervalStarted){
		// 驱动列表实时刷新
		setInterval('refreshDriversList()', 10000);
		$monitorFreshListIntervalStarted = true;
	}
	
	// 绑定驱动块事件
	bindClickEventForDriver();
});
